package com.dhy.takeaway.controller;

import com.dhy.takeaway.entity.Order;
import com.dhy.takeaway.entity.OrderGood;
import com.dhy.takeaway.entity.Res;
import com.dhy.takeaway.entity.StoreOrder;
import com.dhy.takeaway.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
public class OrderController {

    @Autowired
    OrderService orderService;

    @PostMapping("/submitOrder")
    public Res submitOrder(@RequestBody Map<String, Object> map) {
        String orderId = UUID.randomUUID().toString();
        String storeId = (String) map.get("storeId");
        String buyerId = (String) map.get("buyerId");
        String addressId = (String) map.get("addressId");
        List<Map> foods = (ArrayList) map.get("foods");

        List<OrderGood> orderGoods = new ArrayList<>();
        for (Map<String, Object> food : foods) {
            OrderGood orderGood = new OrderGood();
            orderGood.setGoodId((String) food.get("id"));
            orderGood.setOrderId(orderId);
            orderGood.setNum(food.get("num").toString());

            orderGoods.add(orderGood);
        }

        Res res = new Res();
        if (orderService.addOrder(new Order(orderId, storeId, buyerId, addressId))) {
            if (orderService.addOrderGoods(orderGoods)) {
                res.setCode("200");
                res.setMessage("下单成功！");
            } else {
                res.setCode("400");
                res.setMessage("商品list添加错误！");
            }
        } else {
            res.setCode("400");
            res.setMessage("订单错误！");
        }

        return res;
    }

    @PostMapping("/orderList")
    public List<Map> orderList(@RequestBody Map map) {
        String buyerId = (String) map.get("buyerId");
        return orderService.findOrderList(buyerId);
    }

    @PostMapping("/findOrderDetail")
    public List<Map> findOrderById(@RequestBody Map map) {
        String orderId = (String) map.get("orderId");
        return orderService.findOrderDetail(orderId);
    }

    /////////////////商家Business///////////////////////
    @PostMapping("/storeOrderList")
    public List<StoreOrder> storeOrderList(@RequestBody Map map) {
        String id = (String) map.get("userId");
        return orderService.storeOrderList(id);
    }

    @PostMapping("/storeOrderDetail")
    public List<Map> storeOrderDetail(@RequestBody Map map) {
        String id = (String) map.get("orderId");
        return orderService.storeOrderDetail(id);
    }
}